// 网络请求

import axios, { AxiosRequestConfig } from 'axios'

const config: AxiosRequestConfig = {
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 2500, // 请求超时时间
  withCredentials: false, // 是否携带cookie
  headers: {}
}

const checkStatus = (error: any) => {
  switch (error.response.status) {
    case 400:
      error.message = '请求错误'
      break
    case 401:
      error.message = '未授权，请登录'
      break
    case 403:
      error.message = '拒绝访问'
      break
    case 404:
      error.message = `请求地址出错: ${error.response.config.url}`
      break
    case 408:
      error.message = '请求超时'
      break
    case 500:
      error.message = '服务器内部错误'
      break
    case 501:
      error.message = '服务未实现'
      break
    case 502:
      error.message = '网关错误'
      break
    case 503:
      error.message = '服务不可用'
      break
    case 504:
      error.message = '网关超时'
      break
    case 505:
      error.message = 'HTTP版本不受支持'
      break
    default:
      break
  }
  return error
}

// 创建axios实例
const service = axios.create(config)

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers.Authorization = 'Bearer token'
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const data = response.data
    const { code } = data
    // 接口请求成功直接返回数据
    if (code === 0) {
      return data
    } else if (code === -1) {
      // token过期
    }
    return data
  },
  error => {
    if (error && error.response) {
      checkStatus(error)
    }
    Promise.reject(error)
  }
)

/**
 * get请求
 * @param url
 * @param params
 */
export const get = (
  url: string,
  params?: any,
  config: object = {}
): Promise<any> => {
  return service.request({
    url,
    params,
    method: 'GET',
    ...config
  })
}

/**
 * post请求
 * @param url
 * @param data
 */
export const post = (
  url: string,
  data?: any,
  config: object = {}
): Promise<any> => {
  return service.request({
    url,
    data,
    method: 'POST',
    ...config
  })
}

/**
 * delete请求
 * @param url
 * @param data
 */
export const _delete = (url: string, config: Record<string, any> = {}): Promise<any> => {
  return service.request({
    url,
    method: 'DELETE',
    ...config
  })
}

export default service
